//
//  SnapUpProgressView.swift
//  AirTravel
//
//  Created by apple on 2021/8/13.
//

import UIKit
import FWPopupView
import Moya
import SwiftyJSON

protocol SnapUpProgressDelegate:NSObjectProtocol {
    func snapUpProgressClick(dic:Dictionary<String,Any>)
}

class SnapUpProgressView: FWPopupView {
    
    var contentView:UIView!
    weak var delegate: SnapUpProgressDelegate?
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    /// 车次
    @IBOutlet weak var trainsLab: UILabel!
    
    /// 时间
    @IBOutlet weak var timeLab: UILabel!
    
    /// 人员
    @IBOutlet weak var personnelLab: UILabel!
    
    /// 进度
    @IBOutlet weak var progressLab: UILabel!
    
    @IBOutlet weak var progressView: UIProgressView!
    
    var dataStr = ""
    /// 出发站名称
    var fromStationName = ""
    /// 到达站名称
    var toStationName = ""
    /// 车次
    var trainNo = ""
    /// 订单联系人
    var contactName = ""
    var contactMobile = ""
    /// 0、12306下单3块一人       1、平台5块一人
    var platformType = 0
    
    var dataDic : Dictionary<String,Any>?
    var seatDic : Dictionary<String,Any>?
    var passengersArray = [Dictionary<String,Any>]()
    
    var i = 0
    let clickTimer = WMCountDown()
    
    // 初始化时将xib中的view添加进来
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView = loadViewFromNib()
        contentView.frame = self.bounds
        contentView.backgroundColor = UIColor.white
        self.insertSubview(contentView, at: 0)
        
        progressView.setProgress(0, animated: true)
        progressView.observedProgress = Progress.current()
        progressView.progressTintColor = UIColor.init(r: 48, g: 124, b: 248) //进度颜色
        progressView.trackTintColor = UIColor.init(r: 242, g: 243, b: 245) //剩余进度颜色
        //通过改变进度条高度(宽度不变，高度变为默认的2倍)
//        progressView.transform = CGAffineTransform(scaleX: 1.0, y: 2.0)
        
    }
    
    // 初始化时将xib中的view添加进来
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    // 加载xib
    func loadViewFromNib() -> UIView {
        let className = type(of: self)
        let bundle = Bundle(for: className)
        let name = NSStringFromClass(className).components(separatedBy: ".").last
        let nib = UINib(nibName: name!, bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        view.backgroundColor = UIColor.clear
        return view
    }
    
    func setUpData(dataStr:String,fromStationName:String,toStationName:String,trainNo:String,dataDic:Dictionary<String,Any>,seatDic:Dictionary<String,Any>,passengersArray:[Dictionary<String,Any>],contactName:String,contactMobile:String,platformType:Int) {
        self.dataStr = dataStr
        self.fromStationName = fromStationName
        self.toStationName = toStationName
        self.trainNo = trainNo
        self.dataDic = dataDic
        self.seatDic = seatDic
        self.contactName = contactName
        self.contactMobile = contactMobile
        self.passengersArray = passengersArray
        
       " 06:05成都东 - 06:47绵阳"
        
        let array : Array = self.dataStr.components(separatedBy: "-")
 
        
        self.trainsLab.text = "\(self.trainNo)" + " \(array[1])月\(array[2])日" + " \(self.getWeekDay(dateTime: "\(self.dataStr)"))" + " 出发"
        self.timeLab.text = "\(self.dataDic?["startTime"] ?? "")\(self.fromStationName) - \(self.dataDic?["arriveTime"] ?? "")\(self.toStationName)"
 
        
        var namestr = ""
        for (index,item) in self.passengersArray.enumerated() {
            
            print("\(index),\(item)")
   
            let name = "\(item["name"] ?? "")"
 
            if (name != "") {
                namestr = name + "、"
            }
   
        }
        print("\(namestr)")
        namestr.removeLast()
        self.personnelLab.text = namestr
        
        
        self.progressLab.text = "0%"
        self.i = 0
        self.platformType = platformType
        self.progressView.setProgress(0, animated: true)
        ///延迟执行之前的代码
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute:{
            UIView.animate(withDuration: 49) {
                self.progressView.setProgress(0.99, animated: true)
                
            }
        })
        self.clickTimer.countDown = { [weak self] (d, h, m, s) in
            self?.i += 2
            self?.progressLab.text = "\(self?.i ?? 0)%"
        }
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let calendar = Calendar.current
        let date1 = calendar.date(byAdding: .second, value: 50, to: Date())!
        let str = dateFormatter.string(from: date1)
        self.clickTimer.start(with: nil, end: str)
        
        createOrder()
    }

    func getWeekDay(dateTime:String)->String{
        let dateFmt = DateFormatter()
        dateFmt.dateFormat = "yyyy-MM-dd"
        let date = dateFmt.date(from: dateTime)
        let interval = Int(date!.timeIntervalSince1970) + NSTimeZone.local.secondsFromGMT()
        let days = Int(interval/86400) // 24*60*60
        let weekday = ((days + 4)%7+7)%7
        print("\(weekday)")
        
        switch weekday {
        case 0:
            return "周日"
        case 1:
            return "周一"
        case 2:
            return "周二"
        case 3:
            return "周三"
        case 4:
            return "周四"
        case 5:
            return "周五"
        default:
            return "周六"
        }
        
//        return weekday == 0 ? 7 : weekday
    }
    
    @IBAction func cancel(_ sender: Any) {
        self.clickTimer.stop()
        self.hide()
        self.hideKeyboard()
    }
    
    //火车票下单接口
    func createOrder() {
        var parameters = [String:Any]()
        
        
        var arr:[String] = []
        for (index,item) in self.passengersArray.enumerated() {
            
            print("\(index),\(item)")
   
            let id = "\(item["id"] ?? "")"
 
            if (id != "") {
                arr.append(id)
            }
   
        }
        parameters.updateValue(arr, forKey: "passengers")
        
        if platformType == 0 {
            let username = "\(UserDefaults.standard.value(forKey: "12306Login") ?? "")"
            let password12306 = "\(UserDefaults.standard.value(forKey: "12306Password") ?? "")"
            parameters.updateValue(username, forKey: "account12306")
            parameters.updateValue(password12306, forKey: "password12306")
            parameters.updateValue("0", forKey: "accountType")
        }else{
            parameters.updateValue("1", forKey: "accountType")
        }
        parameters.updateValue(self.dataStr, forKey: "departDate")
        parameters.updateValue(self.fromStationName, forKey: "fromStationName")
        parameters.updateValue(self.toStationName, forKey: "toStationName")
        parameters.updateValue(self.trainNo, forKey: "trainNo")
        parameters.updateValue("\(self.seatDic?["maxPrice"] ?? "")", forKey: "ticketPrice")
        parameters.updateValue("\(self.seatDic?["seatType"] ?? "")", forKey: "seatType")
        parameters.updateValue(self.contactName, forKey: "contactName")
        parameters.updateValue(self.contactMobile, forKey: "contactMobile")
        parameters.updateValue("1", forKey: "orderType")
        
        
        
        
        parameters.updateValue("0", forKey: "frontSeatFlag")
        
        
        print("\(parameters)")
        
        
        cancelableRequest = NetWorkRequest(API1.createOrder(parameters: parameters), completion: {[weak self] (responseString) -> (Void) in
            let order_id = responseString["data"]["order_id"].stringValue
            
            self?.delegate?.snapUpProgressClick(dic: ["key":"成功","val":order_id])
            
        }, failed: {[weak self] (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
            self?.delegate?.snapUpProgressClick(dic: ["key":"失败"])
            
        }, errorResult: {[weak self] () -> (Void) in
            print("网络异常")
            self?.delegate?.snapUpProgressClick(dic: ["key":"失败"])
            
        })
    }
}
